package cn.qingyun.gis.modules.scenes.interceptor;

import cn.qingyun.gis.common.Result;
import cn.qingyun.gis.modules.scenes.interceptor.basic.NkResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Optional;

@ControllerAdvice
@Slf4j
public class GlobalResponseInterceptor implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {

        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        boolean needConvert = false;
        try {
            String servletPath = ((ServletServerHttpRequest) request).getServletRequest().getServletPath();
            needConvert = servletPath.startsWith("/app/scenes/photo/query");
        } catch (Exception e) {
            log.error("获取服务路径失败", e);
        }
        if (body instanceof Result && needConvert) {
            Result result = (Result) body;

            NkResult<Object> nkResult = NkResult.builder()
                    .resCode(result.getSuccess() ? "0" : "1")
                    .resDesc(Optional.ofNullable(result.getMessage()).orElse("Ok"))
                    .result(result.getData())
                    .build();

            return nkResult;
        }
        return body;
    }
}
